package com.company.huisuo.biz.dialog

import android.app.Activity
import android.view.WindowManager
import com.company.huisuo.R
import com.company.huisuo.base.BaseCenterPopupView
import com.company.huisuo.databinding.DialogRewardMemberBinding
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class RewardMemberDialog(
    activity: Activity, val onLoginClick: () -> Unit
) : BaseCenterPopupView<DialogRewardMemberBinding>(
    activity
) {
    private var mJob: Job? = null
    private val mainScope = MainScope()

    override val getLayoutId: Int
        get() = R.layout.dialog_reward_member
    override val getViewBinding: DialogRewardMemberBinding
        get() = DialogRewardMemberBinding.bind(contentView)

    override fun initData() {
        // 阻止软键盘自动弹出
        dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)

        mBinding.ivClose.setOnClickListener {
            dismiss()
        }
        mBinding.tvGetCode.setOnClickListener {
            if (mJob?.isActive != true) {
                countDown()
            }
        }
        mBinding.tvLogin.setOnClickListener {
            onLoginClick.invoke()
            dismiss()
        }
    }

    private fun countDown() {
        mJob = mainScope.launch {
            mBinding.tvGetCode.isEnabled = false
            for (i in 60 downTo 1) {
                mBinding.tvGetCode.text = "${i}s"
                delay(1000)
            }
            mBinding.tvGetCode.text = "获取验证码"
            mBinding.tvGetCode.isEnabled = true
        }
    }

    override fun dismiss() {
        super.dismiss()
        mJob?.cancel()
    }

}